//
//  BookFaceViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/1/6.
//  Copyright © 2021 zhangbenchao. All rights reserved.
//


#import "BookFaceViewController.h"
#import "BkFacePublishViewController.h"
#import "BkFaceDetailViewController.h"

#import "MyXindeTableViewCell.h"
#import "BkFaceControlView.h"
#import "LXMessageViewController.h"
#import "LXSaveUserInforTool.h"
#import "ETF_Default_ActionsheetView.h"

@interface BookFaceViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic) NSInteger pageNum;
@property (nonatomic,strong) UIButton *publishBtn;
@property (nonatomic,strong) UIButton *messageBtn;
@property (nonatomic,strong) UITextField *searchTextFiled;
@property (nonatomic,strong) UIImageView *searchImg;
@property (nonatomic,strong) BkFaceControlView *faceHeaderView;

@property (nonatomic,strong) NSString *fid;

@property (nonatomic,strong) NSString *keyWords;

@property (nonatomic,strong) NSMutableArray *blackOrderArray;

@end

@implementation BookFaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view addSubview:self.faceHeaderView];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = kWhiteColor;
    [self navigationConfig];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.messageBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
   
    
}
-(void)historyDataConfig
{
    NSString *docuPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    docuPath =[docuPath stringByAppendingString:@"/blackOrders.txt"];
    //写入文件
    
    //取出文件
    NSArray *array = [NSArray arrayWithContentsOfFile:docuPath];
    if (!array) {
        array = @[];
    }
    self.blackOrderArray = [NSMutableArray arrayWithArray:array];
    [array writeToFile:docuPath atomically:YES];
    NSLog(@"docuPath = %@",docuPath);
}
-(UIButton *)messageBtn{
    if (!_messageBtn) {
        _messageBtn = [TSWLTools allocButtonTitle:@"" font:systemFont(TSScaleW(0)) textColor:kWhiteColor image:[UIImage imageNamed:@"wuxiaoxi"] frame:CGRectMake(0, 0, TSScaleW(40), TSScaleW(40)) sel:@selector(messageAction:) taget:self];
    }
    return _messageBtn;
}
-(void)messageAction:(UIButton *)sender
{
    LXMessageViewController *vc = [[LXMessageViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ----获取未读消息数量

-(void)requstUnreadCount{
    //getmessnum
    [NetWorkTools postConJSONWithUrl:@"getmessnum" parameters:@{} success:^(id responseObject) {
       
        NSString *datastr = responseObject[@"datastr"];
//        if ([result integerValue] == 0) {
//            self.classify1Array = dataList;
//        }else{
//            [MBProgressHUD showError:resultNote];
//        }
        UIView *v = [self.messageBtn viewWithTag:22000000];
        if (v) {
            [v removeFromSuperview];
        }
        if (datastr.intValue !=0) {
           
            UILabel *unreadLabel = [TSWLTools allocLabel:datastr font:systemFont(TSScaleW(8)) textColor:kWhiteColor frame:CGRectMake(TSScaleW(30), TSScaleW(5), TSScaleW(18), TSScaleW(12)) textAlignment:(NSTextAlignmentCenter)];
            unreadLabel.tag = 22000000;
            [self.messageBtn addSubview:unreadLabel];
            unreadLabel.backgroundColor = kRedColor;
            unreadLabel.cornerRadius = unreadLabel.height/2.f;
           
            CGFloat w = [datastr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, TSScaleW(10)) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:systemFont(TSScaleW(8))} context:nil].size.width;
            unreadLabel.width = w + TSScaleW(8);
            unreadLabel.left = self.messageBtn.width - unreadLabel.width;
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self requstUnreadCount];
    [self headerRefresh];
    [self getclassify1listRqust];
}
-(void)navigationConfig{
    self.navigationItem.titleView = self.searchTextFiled;
    [self addLeftNavItemWithImage:[UIImage imageNamed:@"添加"]];
    //[self addRightNavgationItemWithImage:[UIImage imageNamed:@"wuxiaoxi"]];
    
}
#pragma mark ---一级分类请求
-(void)getclassify1listRqust{
    [NetWorkTools postConJSONWithUrl:@"getclassify1list" parameters:@{} success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *dataList = responseObject[@"dataList"];
        if ([result integerValue] == 0) {
            self.classify1Array = dataList;
            [LXSaveUserInforTool sharedUserTool].classify1Array = dataList;
            NSArray *array = [LXSaveUserInforTool sharedUserTool].classify1Array;
            NSMutableArray *nameArray = [NSMutableArray array];
            
            for (int i = 0; i < array.count; i ++) {
                NSDictionary *dic = array[i];
                [nameArray addObject:dic[@"name"]];
                
            }
            [nameArray insertObject:@"全部" atIndex:0];
            self.faceHeaderView.bttonsArray = nameArray;
        }else{
            [MBProgressHUD showError:resultNote];
        }
    } fail:^(NSError *error) {
        
    }];
}
-(void)setClassify1Array:(NSArray *)classify1Array{
    
}
-(BkFaceControlView *)faceHeaderView{
    if (!_faceHeaderView) {
        NSArray *array = [LXSaveUserInforTool sharedUserTool].classify1Array;
        NSMutableArray *nameArray = [NSMutableArray array];
        
        for (int i = 0; i < array.count; i ++) {
            NSDictionary *dic = array[i];
            [nameArray addObject:dic[@"name"]];
            
        }
        [nameArray insertObject:@"全部" atIndex:0];
        _faceHeaderView = [[BkFaceControlView alloc]initWithTop:0 titleArray:nameArray];
        WS(weakSelf);
        _faceHeaderView.btnClickedBlock = ^(NSInteger index) {
            
            if (index>=1) {
                NSDictionary *dic = array[index-1];
                weakSelf.fid = dic[@"fid"];
            }
            if (index == 0) {
                weakSelf.fid = @"";
            }
            
        };
    }
    return _faceHeaderView;
}
-(void)setFid:(NSString *)fid
{
    _fid = fid;
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark ---发布事件
-(void)leftBtnAction:(id)sender{
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    BkFacePublishViewController *vc = [[BkFacePublishViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --消息事件
-(void)rigthBtnAction:(id)sender{
    LXMessageViewController *vc = [[LXMessageViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(UITextField *)searchTextFiled{
    if (!_searchTextFiled) {
        _searchTextFiled = [TSWLTools allocTextFieldTextFont:TSScaleW(14) placeHolderFont:TSScaleW(14) text:nil placeText:@"请输入商品名称进行搜索" textColor:kMainTxtColor placeHolderTextColor:kGrayTxtColor frame:CGRectMake(TSScaleW(12), TSScaleW(10),TSScaleW(260), TSScaleW(27))];
        _searchTextFiled.cornerRadius = _searchTextFiled.height/2.f;
        _searchTextFiled.leftViewMode = UITextFieldViewModeAlways;
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TSScaleW(34), _searchTextFiled.height)];
        [view addSubview:self.searchImg];
        _searchTextFiled.leftView = view;
        _searchTextFiled.backgroundColor = kMainBgColor;
        _searchTextFiled.delegate = self;
    }
    return _searchTextFiled;
}
-(UIImageView *)searchImg{
    if (!_searchImg) {
        _searchImg = [[UIImageView alloc ]initWithFrame:CGRectMake(TSScaleW(15), TSScaleW(9), TSScaleW(12), TSScaleW(12))];
        _searchImg.image = [[UIImage imageNamed:@"搜索"] imageChangeColor:kMainTxtColor];
        _searchImg.centerY = _searchTextFiled.height/2.f;
    }
    return _searchImg;
}

-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, _faceHeaderView.height, TSScreenWidth, TSScreenHeight - Height_NavBar -Height_TabBar - _faceHeaderView.height) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
        if (@available(iOS 11.0, *))
        {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        WS(weakSelf);
        _tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
                [weakSelf headerRefresh];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [weakSelf footerRefresh];
        }];
    }
    return _tableView;
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyXindeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MycomendsTableViewCell"];
    if (!cell) {
        cell = [[MyXindeTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"MycomendsTableViewCell"];
  
    }
    cell.secDic = self.dataArray[indexPath.row];
    cell.isOn =  [LXSaveUserInforTool sharedUserTool].status.integerValue;
    WS(weakSelf);
    NSDictionary *d = self.dataArray[indexPath.row];
    cell.isBlackBlock = ^{
        [weakSelf showAlertWith:d];
    };
    return cell;
}
-(void)showAlertWith:(NSDictionary *)dic
{
    
     WS(weakSelf);
     NSArray *array = @[@"拉黑",@"举报"];
     [ETF_Default_ActionsheetView showWithItems:array title:@"" selectedIndexBlock:^(NSInteger selectIndex) {
         if (selectIndex == 0) {
             [weakSelf blackAction:dic];
         }else{
             [weakSelf jubaoAction];
         }
         } cancleBlock:^{
                    
     }];
}
-(void)jubaoAction{
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:@"举报成功!"];
       
    });
}
-(void)blackAction:(NSDictionary *)dic
{
    if (![self.blackOrderArray containsObject:dic[@"did"]]) {
        [self.blackOrderArray addObject:dic[@"did"]];
      
    }
    [self  saveToPhone];
}

-(void)saveToPhone
{
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:@"拉黑成功!"];
        NSString *docuPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
        docuPath =[docuPath stringByAppendingString:@"/blackOrders.txt"];
        [self.blackOrderArray writeToFile:docuPath atomically:YES];
        [self historyDataConfig];
        [self headerRefresh];
    });
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    BkFaceDetailViewController *vc = [[BkFaceDetailViewController alloc]init];
    NSDictionary *dic = self.dataArray[indexPath.row];
    vc.did =dic[@"did"];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TSScaleW(245);
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectZero];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TSScreenWidth, 0)];
    view.backgroundColor = kMainBgColor;
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}

#pragma mark - 上拉、下拉

-(void)headerRefresh
{
    NSString *state = [LXSaveUserInforTool sharedUserTool].status;
     if (!state.integerValue) {
         [self historyDataConfig];
     }else{
        
     }
    self.pageNum = 1;
    [self collectListReq];
}

-(void)footerRefresh
{
    [self collectListReq];
}
-(void)collectListReq
{
    NSDictionary *pamas = @{@"pageNo":[NSString stringWithFormat:@"%ld",self.pageNum],@"pageSize":[NSString stringWithFormat:@"%d",kPage_Size],@"fid":_fid,
                            @"content":_keyWords?:@""
    };
   
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetWorkTools postConJSONWithUrl:@"getdynamiclist" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *array = responseObject[@"dataList"];
        if (result.integerValue == 0) {
           
            [self handleListWithModel:array];
        }else{
             [MBProgressHUD showError:resultNote];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(void)endRefrash

{
    if (self.tableView.mj_header.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    if (self.tableView.mj_footer.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
}
-(void)handleListWithModel:(NSArray *)result
{
    
    if (self.pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    if (result.count != kPage_Size) {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }else{
        self.tableView.mj_footer.state = MJRefreshStateIdle;
    }
   NSString *state = [LXSaveUserInforTool sharedUserTool].status ;
    if (!state.integerValue) {
        for (int i = 0; i < result.count; i ++) {
            NSDictionary *dic = result[i];
            NSString *did = dic[@"did"];
            if (self.blackOrderArray.count) {
                BOOL have = NO;
                for (NSString *s in self.blackOrderArray) {
                    if ([s isEqual:did]) {
                        have = YES;
                        break;
                    }
                    
                }
                if (!have) {
                    [self.dataArray addObject:dic];
                }else{
                    
                }
               
            }else{
                [self.dataArray addObject:dic];
            }
            
        }
    }else{
        [self.dataArray addObjectsFromArray:result];
    }
    
  //
   
   [SSKJ_NoDataView showNoData:self.dataArray.count toView:self.tableView offY:TSScaleW(10) message:@"还没有数据哦~" imge:[UIImage imageNamed:@"nolikesimg"]];
    
    self.pageNum++;
    
    [self endRefrash];
    
    [self.tableView reloadData];
    
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    NSString *contentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    if (contentString==nil) {
//        contentString = @"";
//    }
   // self.searchTextFiled.text = contentString;
    
    NSString *contentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    _keyWords = contentString;
    [self.tableView.mj_header beginRefreshing];
    
    
    return YES;
}
@end
